﻿using System;
using System.Configuration;
using System.Text;
using System.Web.Http;
using FellowshipOne.API;
using FellowshipOne.API.Base;
using FellowshipOne.API.People.Model;
using MasVida.WebApi.Controllers.Interfaces;
using MasVida.WebApi.Models.DataObject;
using MasVida.WebApi.Models.Requests;
using MasVida.WebApi.Models.Responses;

namespace MasVida.WebApi.Controllers
{
    public class LoginController : ApiBaseController
    {
        
        public LoginController()
        {
            FellowshipOneClient = new FellowshipOneClient();
        }

        public LoginController(IFellowshipOneClient fellowshipOneClient)
        {
            FellowshipOneClient = fellowshipOneClient;
        }

        [AcceptVerbs("GET")]
        public LoginRequest Index()
        {
            return new LoginRequest(){LoginType = LoginType.PortalUser};
        }

        public LoginResponse Login(LoginRequest loginRequest)
        {
            LoginResponse response = new LoginResponse();

            if (loginRequest == null || string.IsNullOrEmpty(loginRequest.Username) ||
                string.IsNullOrEmpty(loginRequest.Password))
            {
                response.ErrorMessage = "Username and/or password can not be empty";
                return response;
            }

            try
            {
                F1OAuthTicket ticket = new F1OAuthTicket
                {
                    ConsumerKey = ConfigurationManager.AppSettings["Consumer.Key"],
                    ConsumerSecret = ConfigurationManager.AppSettings["Consumer.Secret"],
                    ChurchCode = ConfigurationManager.AppSettings["Church.Code"],
                };
                bool isStaging = Boolean.Parse(ConfigurationManager.AppSettings["IsStaging"]);
                F1OAuthTicket requestTokenAuthTicket = FellowshipOneClient.GetRequestToken(ticket, isStaging, isStaging);

                F1OAuthTicket accessTokenAuthTicket = FellowshipOneClient.Authorize(requestTokenAuthTicket,
                    loginRequest.Username, loginRequest.Password, loginRequest.LoginType, isStaging, isStaging);
                IRestClient restClient = GetRestClient(accessTokenAuthTicket);

                string personUrl = accessTokenAuthTicket.PersonURL;
                string personIdString = personUrl.Substring(personUrl.LastIndexOf("/") + 1, personUrl.Length - personUrl.LastIndexOf("/") - 1);
                response.PersonId = int.Parse(personIdString);
                Person person = restClient.PeopleRealm.People.Get(personIdString);
                response.Name = $"{person.FirstName} {person.LastName}";
                response.Success = true;
                response.AccessTicket = new OAuthTicketDo(accessTokenAuthTicket);
            }
            catch (Exception ex)
            {
                response.ErrorMessage = ex.Message;
            }
            return response;
        }
    }
}
